//
//  ChatBottomView.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/10/29.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "ChatBottomView.h"
#import "XKO_CreateUIViewHelper.h"
#import <AVFoundation/AVFoundation.h>
#import "RecordView.h"
#import <iflyMSC/iflyMSC.h>
#import "JSONKit.h"
#import "AudioConverter.h"
#import "NSString+Teshuzifu.h"
#import "UploadFile.h"
#import "ZYQAssetPickerController.h"

@interface ChatBottomView()<IFlySpeechRecognizerDelegate,UINavigationControllerDelegate, ZYQAssetPickerControllerDelegate>
{
    AVAudioRecorder *_recorder;
//    NSTimer *_timer;
}

@property(nonatomic, strong) NSMutableString *lastSpeekString;
@property(nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;
@property(nonatomic, strong) ZYQAssetPickerController *picker;

@end

@implementation ChatBottomView

- (void)dealloc {
    
//    [_timer invalidate];
//    _timer = nil;
}

- (id)initWithFrame:(CGRect)frame sendMessageBlock:(SendMessageBlock)messageBlock recordFinishBlock:(RecordFinishBlock)recordFinishBlock sartIFlySpeechBlock:(StartIFlySpeechBlock)startIFlySpeechBlock addPictureBlock:(AddPictureBlock)addPictureBlock{
    
    if (self = [super initWithFrame:frame]) {
        
        self.sendMessageBlock = messageBlock;
        self.recordFinishBlock = recordFinishBlock;
        self.startIFlySpeechBlock = startIFlySpeechBlock;
        self.addPictureBlock = addPictureBlock;
        
        self.textBackgroundView.backgroundColor = [UIColor blackColor];
        self.voiceBackgroundView.backgroundColor = kGetColor(18, 38, 74);
        
        [self addSubview:self.textBackgroundView];
        [self addSubview:self.voiceBackgroundView];
        self.lastSpeekString = [[NSMutableString alloc] init];
        
        //开启本地录音
//        [self initRecord];
    }
    
    return self;
}

#pragma mark - getter/setter

- (UIView *)voiceBackgroundView {
    
    if (!_voiceBackgroundView) {
        
        _voiceBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        [_voiceBackgroundView addSubview:self.changeTextBtn];
        [_voiceBackgroundView addSubview:self.recordBtn];
        [_voiceBackgroundView addSubview:self.settingBtn];
        
        [self.changeTextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_voiceBackgroundView.mas_left).with.offset(10);
            make.centerY.equalTo(_voiceBackgroundView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];

        [self.recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_voiceBackgroundView.mas_centerX);
            make.centerY.equalTo(_voiceBackgroundView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];

        [self.settingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_voiceBackgroundView.mas_right).with.offset(-10);
            make.centerY.equalTo(_voiceBackgroundView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];
    }
    
    return _voiceBackgroundView;
}

- (UIView *)textBackgroundView {
    
    if (!_textBackgroundView) {
        
        _textBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        [_textBackgroundView addSubview:self.changeVoiceBtn];
        [_textBackgroundView addSubview:self.inputTextField];
        [_textBackgroundView addSubview:self.sendBtn];

        [self.changeVoiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_textBackgroundView.mas_left).with.offset(10);
            make.centerY.equalTo(_textBackgroundView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(32, 32));
        }];
        
        [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_textBackgroundView.mas_right).with.offset(-10);
            make.centerY.equalTo(_textBackgroundView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(57, 32));
        }];

        [self.inputTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.changeVoiceBtn.mas_right).with.offset(10);
            make.right.equalTo(self.sendBtn.mas_left).with.offset(-5);
            make.centerY.equalTo(_textBackgroundView.mas_centerY);
            make.height.equalTo(@32);
        }];
    }
    
    return _textBackgroundView;
}

- (UIButton *)changeTextBtn {
    
    if (!_changeTextBtn) {
        
        _changeTextBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"Keyboard") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_changeTextBtn addTarget:self action:@selector(changeTextBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _changeTextBtn;
}

- (UIButton *)recordBtn {
    
    if (!_recordBtn) {
        
        _recordBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"Microphone") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_recordBtn addTarget:self action:@selector(speakBtnDown:) forControlEvents:UIControlEventTouchDown];
        [_recordBtn addTarget:self action:@selector(speakBtnDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [_recordBtn addTarget:self action:@selector(speakBtnUpOut:) forControlEvents:UIControlEventTouchUpOutside];
        [_recordBtn addTarget:self action:@selector(speakBtnUp:) forControlEvents:UIControlEventTouchUpInside];
        [_recordBtn addTarget:self action:@selector(speakBtnUpOut:) forControlEvents:UIControlEventTouchCancel];
        
    }
    
    return _recordBtn;
}

- (UIButton *)settingBtn {
    
    if (!_settingBtn) {
        
        _settingBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"setup") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_settingBtn addTarget:self action:@selector(settingBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    }
    
    return _settingBtn;
}

- (UIButton *)changeVoiceBtn {
    
    if (!_changeVoiceBtn) {
        
        _changeVoiceBtn = [XKO_CreateUIViewHelper createUIButtonWithNormalImage:IMAGE(@"mike") highlightedImage:nil radiusSize:0 frame:CGRectZero];
        [_changeVoiceBtn addTarget:self action:@selector(changeVoiceBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _changeVoiceBtn;
}

- (UIButton *)sendBtn {
    
    if (!_sendBtn) {
        
        _sendBtn = [XKO_CreateUIViewHelper createUIButtonWithTitle:@"发送" titleColor:[UIColor whiteColor] titleFont:kFontSize14 backgroundColor:kGetColor(0, 160, 234) hasRadius:NO targetSelector:@selector(sendBtnClicked:) target:self];
    }
    
    return _sendBtn;
}

- (UITextField *)inputTextField {
    
    if (!_inputTextField) {
        
        _inputTextField = [XKO_CreateUIViewHelper createUITextFieldWithFrame:CGRectZero placeholder:@"请输入验证码" backgroundColor:[UIColor whiteColor]];
        _inputTextField.delegate = self;
    }
    
    return _inputTextField;
}

- (RecordView *)recordView {
    
    if (!_recordView) {
        _recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 160, 160)];
        _recordView.center = CGPointMake(self.frame.size.width/2, 300);
    }
    
    return _recordView;
}

- (IFlySpeechRecognizer *)iFlySpeechRecognizer {
    
    if (!_iFlySpeechRecognizer) {
        //1.创建语音听写对象
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        _iFlySpeechRecognizer.delegate = self;
        //设置听写模式
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        //2.设置听写参数
        [_iFlySpeechRecognizer setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
        
        //asr_audio_path是录音文件名,设置value为nil或者为空取消保存,默认保存目录在 Library/cache下。
        [_iFlySpeechRecognizer setParameter:@"luyin.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    }
    
    return _iFlySpeechRecognizer;
}

- (ZYQAssetPickerController *)picker {
    
    if (!_picker) {
        _picker = [[ZYQAssetPickerController alloc] init];
        _picker.maximumNumberOfSelection = 1;
        _picker.assetsFilter = [ALAssetsFilter allPhotos];
        _picker.showEmptyGroups=NO;
        _picker.delegate=self;
        _picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
    }
    
    return _picker;
}

#pragma mark - private methord

- (void)initRecord
{
    NSDictionary *recordSettings = @{AVFormatIDKey:[NSNumber numberWithInt:kAudioFormatLinearPCM],
                                     AVSampleRateKey:@11025.0,
                                     AVNumberOfChannelsKey:@2,
                                     AVLinearPCMBitDepthKey:@16,
                                     AVEncoderAudioQualityKey:[NSNumber numberWithInt:AVAudioQualityMin]};
    NSURL *recordedFile = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingString:@"/Documents/luyin.caf"]];
    _recorder = [[AVAudioRecorder alloc] initWithURL:recordedFile settings:recordSettings error:nil];
    //开启音量检测
    _recorder.meteringEnabled = YES;
    [_recorder prepareToRecord];
}

- (void)detectionVoice
{
    //刷新音量数据
    [_recorder updateMeters];
    double lowPassResults = pow(10, (0.05 * [_recorder peakPowerForChannel:0]));
    [self.recordView updateAnimateViewWithVolume:lowPassResults];
}

#pragma mark - event

- (void)changeTextBtnClicked:(UIButton *)sender {
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 50);
        
    } completion:^(BOOL finished) {
        
        self.frame = CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50);
        [self bringSubviewToFront:_textBackgroundView];

    }];

}

- (void)changeVoiceBtnClicked:(UIButton *)sender {
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 50);
        
    } completion:^(BOOL finished) {
        
        self.frame = CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50);
        [self bringSubviewToFront:_voiceBackgroundView];
        [_inputTextField resignFirstResponder];
        
    }];

}

- (void)settingBtnClicked:(UIButton *)sender {
    
    [self addPicture];
    
}

- (void)sendBtnClicked:(UIButton *)sender {
    
    if (_sendMessageBlock) {
        _sendMessageBlock(_inputTextField.text,AudioNormalType);
        _inputTextField.text = @"";
        [_inputTextField resignFirstResponder];
    }
}

- (void)speakBtnDown:(UIButton *)button
{
    [self.recordView updateAnimateViewWithVolume:0.45];

    //科大讯飞录音
    [self.iFlySpeechRecognizer startListening];
    
    if (!self.recordView.superview) {
        [kCurrentKeyWindow addSubview:self.recordView];
    }
    
//    //本地录音
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryRecord error:nil];
//    [session setActive:YES error:nil];
//
//    [_recorder record];
//    _timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
    
}

- (void)speakBtnDragExit:(UIButton *)button
{
    self.recordView.title.text = @"松开手指，取消发送";
    self.recordView.title.backgroundColor = kGetColor(150, 30, 30);
    [self.recordView removeFromSuperview];
}

- (void)speakBtnUpOut:(UIButton *)button
{
//    [_recorder deleteRecording];
//    [_recorder stop];
//    [_timer invalidate];
    
    self.recordView.title.text = @"上滑手指，取消发送";
    self.recordView.title.backgroundColor = [UIColor clearColor];
    [self.recordView removeFromSuperview];
}

- (void)speakBtnUp:(UIButton *)button
{
    [self.recordView removeFromSuperview];
    
    //科大讯飞停止录音
    [self.iFlySpeechRecognizer stopListening];

//    double time = _recorder.currentTime;
//    
//    [_recorder deleteRecording];
//    [_recorder stop];
//    [_timer invalidate];
//    
//    if (time < 1) {
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kCurrentKeyWindow animated:YES];
//        hud.mode = MBProgressHUDModeText;
//        hud.labelText = @"您能多说点吗，起码要1秒哦！";
//        hud.removeFromSuperViewOnHide = YES;
//        [hud hide:YES afterDelay:1];
//        
//        return;
//    }
//    
//    if (_recordFinishBlock) {
//        _recordFinishBlock(time);
//    }
}

- (void)convertToMp3WithSpeekString:(NSString *)speekString {
    
    NSString *file = kPathOfPCM;
    NSData *data = [AudioConverter convertToMp3OfPath:file];
    
    if (data) {
        
        NSString *fileName = [NSString getUniqueStrByUUID] ;
        NSString *filePath = [[FileMangeHelper shareInstance] getUploadPathFromFileType:UploadFileAudioType];
        
        [[FileMangeHelper shareInstance] copyFileWithFromPath:kPathOfMP3 toPath:filePath fileName:fileName];
        
        if (_startIFlySpeechBlock) {
            _startIFlySpeechBlock(speekString,UploadFileAudioType,nil,[NSString stringWithFormat:@"%@.mp3",fileName],CGSizeZero);
        }
        
        NSString *postUrl = [NSString stringWithFormat:@"http://%@:%d/upload",kUploadIP,KUploadPort];
        WEAK_SELF
        [[UploadFile shareInstance] upLoadFileWithURL:postUrl data:data type:IMAudioUploadFileType uploadFileSuccess:^(NSDictionary *resultDic) {
            
            if (!IsEmpty(resultDic[@"url"])) {
                
                if (weak_self.startIFlySpeechBlock) {
                    weak_self.startIFlySpeechBlock(speekString,UploadFileAudioType,resultDic[@"url"],[NSString stringWithFormat:@"%@.mp3",fileName],CGSizeZero);
                }
            }
        }];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (_sendMessageBlock) {
        _sendMessageBlock(textField.text,AudioNormalType);
        textField.text = @"";
        [textField resignFirstResponder];
    }
    
    return YES;
}

#pragma mark - IFlySpeechRecognizerDelegate

/*识别结果返回代理
 @param :results识别结果
 @ param :isLast 表示是否最后一次结果
 */
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast {
    
    NSLog(@"ifReadOnly value: %@" ,isLast?@"YES":@"NO");
    
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *firstDic = results [0];
    for (NSString *key in firstDic) {
        
        NSDictionary *secondDic = [key objectFromJSONString];
        NSArray *firstList = secondDic[@"ws"];
        for (NSDictionary *thirdDic in firstList) {
            
            NSArray *secondList = thirdDic[@"cw"];
            for (NSDictionary *fourthDic in secondList) {
                if (fourthDic[@"w"]) {
                    [resultString appendFormat:@"%@",fourthDic[@"w"]];
                }
            }
        }
    }
    
    if (!IsEmpty(resultString)) {
        [self.lastSpeekString appendString:resultString];
    }
    
    if (isLast && !IsEmpty(self.lastSpeekString)) {
        
        [self convertToMp3WithSpeekString:self.lastSpeekString];
        self.lastSpeekString = [[NSMutableString alloc] init];
        [self.recordView removeFromSuperview];
    }
}

/**
 *  识别会话结束返回代理
 *
 *  @param error 错误码,error.errorCode=0表示正常结束,非0表示发生错误。
 */
- (void)onError: (IFlySpeechError *)error{
    
    if (error.errorCode == 0) {
        
        NSLog(@"录音成功!");
        
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kCurrentKeyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = error.errorDesc;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
    }
}

/**
 *  开始录音回调
 */
- (void) onBeginOfSpeech {
    
    
}

/**
 *  停止录音回调
 */
- (void)onEndOfSpeech {
    
}

/**
 *  音量回调函数
 *
 *  @param volume volume 0-30
 */
- (void)onVolumeChanged:(int)volume {
    
    //    double lowPassResults = pow(10, (0.05 * volume));
    //    [self.chatBottomView.recordView updateAnimateViewWithVolume:lowPassResults];
    
}

#pragma mark - 从相册获取图片
#pragma mark - ZYQAssetPickerControllerDelegate

- (void)addPicture
{
    [kCurrentKeyWindow addSubview:self.picker.view];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    if (IsEmpty(assets)) {
        
        [picker.view removeFromSuperview];
        return;
    }
    ALAsset *asset=assets[0];
    UIImage *selectedImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
    [picker.view removeFromSuperview];
    
    NSString *fileName = [[FileMangeHelper shareInstance] saveUploadImageWithImage:selectedImg];
    
    NSString *postUrl = [NSString stringWithFormat:@"http://%@:%d/upload",kUploadIP,KUploadPort];
    NSData *data = UIImageJPEGRepresentation(selectedImg, 0.3);
    
    UIImage *newImg = [UIImage imageWithData:data];
    CGSize imgRect = [Util resetImageSizeFromSourceSize:newImg.size maxWidth:KImageWidth maxHeight:KImageHeight];
    
    if (_startIFlySpeechBlock) {
        _startIFlySpeechBlock(@"图片",UploadFileImageType,nil,fileName,imgRect);
    }
    
    WEAK_SELF
    [[UploadFile shareInstance] upLoadFileWithURL:postUrl data:data type:IMImageUploadFileType uploadFileSuccess:^(NSDictionary *resultDic) {
        
        if (!IsEmpty(resultDic[@"url"])) {
            
            if (weak_self.startIFlySpeechBlock) {
                weak_self.startIFlySpeechBlock(@"图片",UploadFileImageType,resultDic[@"url"],fileName,imgRect);
            }
        }
    }];
}

-(void)assetPickerControllerDidCancel:(ZYQAssetPickerController *)picker {
    
    [picker.view removeFromSuperview];
}


@end
